package com.hxzy.framework.feign;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.hxzy.framework.common.constant.AuthConstant;
import com.hxzy.framework.common.constant.RedisConstant;
import com.hxzy.framework.common.resp.UserDto;
import com.hxzy.framework.web.util.WebFrameworkUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * feign 请求头处理(为远程调用的http请求传递必须的参数)
 *
 * @author Administrator
 */
@Component
public class FeignInterceptor implements RequestInterceptor {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 为feign创建的RestTemplate添加商家ID
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //先从redis中获取缓存
        UserDto backUserInfo =redisBackUserInfo();
        if (ObjectUtil.isNotEmpty(backUserInfo)) {
            requestTemplate.header(AuthConstant.MERCHANT_ID, Long.toString(backUserInfo.getMerchantId()));
        } else {
            String mechantId = WebFrameworkUtils.getRequest().getHeader(AuthConstant.MERCHANT_ID);
            if(StrUtil.isNotBlank(mechantId)) {
                requestTemplate.header(AuthConstant.MERCHANT_ID, mechantId);
            }
        }
    }

    /**
     * 通过令牌获取用户信息
     * @return
     */
    private UserDto redisBackUserInfo(){
        String token = WebFrameworkUtils.getRequest().getHeader(AuthConstant.JWT_TOKEN_HEADER);
        if (ObjectUtil.isEmpty(token)){
            return null;
        }
        String  key= RedisConstant.REQUEST_USER_INFO+token;
        Object  redisValue = redisTemplate.opsForValue().get(key);
        if(Objects.nonNull(redisValue)) {
            //更新过期时间 1天
            redisTemplate.expire(key, 24, TimeUnit.HOURS);
            UserDto userDto = (UserDto) redisValue;
            return userDto;
        }
        return null;
    }
}